#include "recmsgthread.h"
#include "chatdialog.h"

#ifdef _cplusplus
extern "C" {
#endif

#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#ifdef _cplusplus
}
#endif

RecMsgThread::RecMsgThread(QObject *parent) :
    QThread(parent)
{
}

void RecMsgThread::run() {
    int in_msg_sock, bytes_read = 0;
    char* msg = (char*) malloc(65536);
    if(!(in_msg_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)))
        perror("rec socket error : ");
    struct sockaddr_in msg_rec_serv, incoming_info;
    socklen_t size_incoming = sizeof(incoming_info);
    memset((void *) &msg_rec_serv, 0, sizeof(msg_rec_serv));
    memset((void *) &incoming_info, 0, sizeof(incoming_info));
    msg_rec_serv.sin_family = AF_INET;
    msg_rec_serv.sin_port = htons(22299);
    msg_rec_serv.sin_addr.s_addr = INADDR_ANY;
    if(bind(in_msg_sock, (struct sockaddr*) &msg_rec_serv, sizeof(msg_rec_serv)))
        perror("rec bind error");
    while(1) {
        bytes_read = recvfrom(in_msg_sock, msg, 65536, 0,  (struct sockaddr*)&incoming_info, &size_incoming);
        msg[bytes_read] = 0;
        emit msgAvailable(incoming_info, msg);
            //char *ip_address;
            //inet_ntop(AF_INET,
            //ChatWindow newChat()

    }
}
